package com.shigu.mo.actions;

import com.alibaba.fastjson.JSONObject;
import com.shigu.admin.common.service.OemSystemService;
import com.shigu.agent.enums.UserRoleType;
import com.shigu.agent.exceptions.YeepayException;
import com.shigu.agent.processes.BusinessProcess;
import com.shigu.component.shiro.AuthorityUser;
import com.shigu.component.shiro.CaptchaUsernamePasswordToken;
import com.shigu.component.shiro.CustomCredentialsMatcher;
import com.shigu.main4.tools.OssIO;
import com.shigu.mo.bo.MsgedCallbackBO;
import com.shigu.mo.bo.PayedCallbackBO;
import com.shigu.mo.bo.SettlementCallbackBO;
import com.shigu.mo.bo.requests.*;
import com.shigu.mo.enums.CardType;
import com.shigu.mo.enums.SessionEnum;
import com.shigu.mo.exceptions.MoException;
import com.shigu.mo.services.BusinessService;
import com.shigu.mo.services.OverallSituationService;
import com.shigu.mo.utils.*;
import com.shigu.mo.vo.*;
import com.shigu.mo.vo.responses.*;
import com.shigu.passageway.Passageway;
import com.shigu.passageway.exceptions.PassagewayException;
import com.shigu.passageway.exceptions.UnpayException;
import com.shigu.passageway.processes.YeepayPassageway;
import com.shigu.wx.web.services.WxOpenidService;
import com.unpay.skb.responses.ConsumptionResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.sword.wechat4j.WechatCore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

/**
 * 商户操作
 * Created by Licca on 17/11/15.
 */
@Controller
@RequestMapping("/bus/")
public class BusinessController {
    private static final Logger logger = LoggerFactory.getLogger(BusinessController.class);

    @Autowired
    MsgUtil msgUtil;

    @Autowired
    BusinessProcess businessProcess;

    @Autowired
    OemSystemService oemSystemService;

    @Autowired
    BusinessService businessService;

    @Autowired
    WxOpenidService wxOpenidService;

    @Autowired
    OverallSituationService overallSituationService;

    @Autowired
    OssIO ossIO;

    @Value("${main_host}")
    private String host;

    @Value("${wap.kefuQrImg}")
    private String KEFUQR_IMG;

    @Value("${unpay.frontUrl}")
    private String UNPAY_FRONTURL;



    /**
     * 页面登出
     * @return
     */
    @RequestMapping("userout")
    public String loginOut(HttpSession session){
        Subject currentUser = SecurityUtils.getSubject();
        String openid= (String) session.getAttribute(SessionEnum.WX_LOGEDUSER.toString());
        currentUser.logout();
        wxOpenidService.logout(openid);
        if (currentUser.hasRole(UserRoleType.AGENT.getValue())) {
            return "redirect:"+host+"wappage/agpage/agentLogin";
        }else{
            return "redirect:"+host+"wappage/buspage/login";
        }

    }

    /**
     * 商户登陆
     * @param bo
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public LoginResponse login(@Valid LoginRequest bo, HttpServletRequest request,HttpSession session, BindingResult result) throws IOException {
        LoginResponse response=new LoginResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        String openid= (String) session.getAttribute(SessionEnum.WX_LOGEDUSER.toString());
        Subject currentUser = SecurityUtils.getSubject();
        CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken("default",
                bo.getTelephone(), bo.getPassword(), false, request.getRemoteAddr(), "");
            token.setRememberMe(true);
        try {
            currentUser.login(token);
            AuthorityUser auth= (AuthorityUser) currentUser.getSession().getAttribute(SessionEnum.LOGIN_USER.toString());
            wxOpenidService.login(openid,auth.getUserId());
            if (!currentUser.hasRole(UserRoleType.BUSINESS.getValue())) {//不是商户不能登陆
                currentUser.logout();
                wxOpenidService.logout(openid);
//                return response.error("本账户没有商户权限");
                response.setNoRole(true);
            }
        } catch (AuthenticationException e) {
            return response.error("账号或密码错误");
        }
        return response.success();
    }

    /**
     * 提交注册请求
     * @return
     */
    @RequestMapping("submitRegedit")
    @ResponseBody
    public RegeditResponse submitRegedit(@Valid RegeditRequest bo,BindingResult result,HttpServletRequest request,HttpSession session) throws IOException {
        RegeditResponse response=new RegeditResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        String code= (String) session.getAttribute(SessionEnum.VALI_CODE.toString());
        if (!bo.getValiCode().equals(code)) {
            return response.error("请输入正确的验证码");
        }
        Long fromUserId=businessService.parseRegeditFromId(bo.getFromid(),session);
        businessProcess.createBusinessman(oemSystemService.selUserOemTag(fromUserId)
                ,bo.getTelephone(), CustomCredentialsMatcher.encrypt(bo.getPassword()),fromUserId);
        LoginRequest loginRequest=new LoginRequest();
        loginRequest.setTelephone(bo.getTelephone());
        loginRequest.setPassword(bo.getPassword());
        login(loginRequest,request,session,result);
        return response.success();
    }

    /**
     * 获取注册手机验证码
     * @return
     */
    @RequestMapping("getRegeditValiCode")
    @ResponseBody
    public ValiCodeResponse getRegeditValiCode(@Valid ValiCodeRequest bo,BindingResult result,HttpSession session) throws MoException {
        ValiCodeResponse response=new ValiCodeResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }

        try {
            businessService.selUserIdByUserName(bo.getTelephone());
            return response.error("用户已存在不能重复注册");
        } catch (MoException e) {
        }
        String code= (String) session.getAttribute(SessionEnum.VALI_CODE.toString());//如果session里还有这个验证码，那么重发一次
        if (code == null) {
            code= RedomUtil.redomNumber(6);
            session.setAttribute(SessionEnum.VALI_CODE.toString(),code);
        }
        msgUtil.sendValiMsg(bo.getTelephone(),code);
//        System.out.println(code);
        return response.success();
    }

    /**
     * 获取忘记密码手机验证码
     * @return
     */
    @RequestMapping("getForgetPswValiCode")
    @ResponseBody
    public ValiCodeResponse getForgetPswValiCode(@Valid ValiCodeRequest bo,BindingResult result,HttpSession session) throws MoException {
        ValiCodeResponse response=new ValiCodeResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        Long userId=businessService.selUserIdByUserName(bo.getTelephone());
        if (userId == null) {
            return response.error("手机号对应的用户不存在");
        }
        String code= (String) session.getAttribute(SessionEnum.FORGET_PWD.toString());//如果session里还有这个验证码，那么重发一次
        if (code == null) {
            code= RedomUtil.redomNumber(6);
            session.setAttribute(SessionEnum.FORGET_PWD.toString(),code);
        }
        msgUtil.sendValiMsg(bo.getTelephone(),code);
//        System.out.println(code);
        return response.success();
    }

    /**
     * 重置密码
     * @param bo
     * @param result
     * @return
     */
    @RequestMapping("toValiSetNewPsw")
    @ResponseBody
    public SetNewPswResponse toValiSetNewPsw(@Valid SetNewPswRequest bo,BindingResult result,HttpSession session) throws MoException {
        SetNewPswResponse response=new SetNewPswResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        Long userId=businessService.selUserIdByUserName(bo.getTelephone());
        String code= (String) session.getAttribute(SessionEnum.FORGET_PWD.toString());
        if (StringUtils.isEmpty(code)) {
            throw new MoException("请输入验证码");
        }
        if (bo.getValiCode().equals(code)) {
            session.setAttribute(SessionEnum.TEMP_LOGUSER.toString(),userId);
        }
        return response.success();
    }

    /**
     * 获取卡信息
     * @return
     */
    @RequestMapping("getCardData")
    @ResponseBody
    public CardDataResponse getCardData(HttpSession session) throws MoException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        CardDataResponse response=new CardDataResponse();
        //如果没绑定也直接返回空
        if (!businessService.hasRealBind(auth.getUserId())) {
            return response.success("未实名认证");
        }
        //得到储蓄卡
        CardVO cash=businessService.selMyCashCard(auth.getUserId());
        //如果储蓄卡没有，也没有必要查信用卡，直接空返回
        if (cash == null) {
            return response.success();
        }
        response.setCashCardId(cash.getCardId().toString());
        response.setCashCard(cash.getSimple());
        CardVO credit=businessService.selLastUsedCard(auth.getUserId());
        if (credit != null) {
            response.setCreditCardId(credit.getCardId().toString());
            response.setCreditCard(credit.getSimple());
        }
//        response.setMyRate(businessService.selMyRate(auth.getUserId()));
        response.setSystemMsg(overallSituationService.selSystemMsg());
        response.setKefuQrImg(KEFUQR_IMG);
        return response.success();
    }

    /**
     * 获取储蓄卡信息
     * @param session
     * @return
     */
    @RequestMapping("getCashCardData")
    @ResponseBody
    public CashCardDataResponse getCashCardData(HttpSession session) throws MoException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        CashCardDataResponse response=new CashCardDataResponse();
        //得到储蓄卡
        CardVO cash=businessService.selMyCashCard(auth.getUserId());
        if (cash == null) {
            return response.error();
        }
        response.setUserRealName(cash.getRealName());
        response.setIdentificationCard(cash.getBodyNumber());
        return response.success();
    }

    /**
     * 上传银行卡图片
     * @return
     */
    @RequestMapping("postCashImg")
    @ResponseBody
    public PostCashImgResponse postCashImg(HttpServletRequest req,HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        PostCashImgResponse response=new PostCashImgResponse();
        try {
            JSONObject obj=paramFromReader(req.getReader());
            String baseImg=obj.getString("cashCardImg");
            if (StringUtils.isEmpty(baseImg)) {
                return response.error();
            }
            response.setCashCard(businessService.postCashImg(auth.getUserId(),baseImg));
        } catch(Exception e) {
            return response.error();
        }
        return response.success();
    }

    /**
     * 上传身份证进行OCR
     * @return
     */
    @RequestMapping("postIdentificationCardImg")
    @ResponseBody
    public PostIdentificationResponse postIdentificationCardImg(HttpServletRequest req,HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        PostIdentificationResponse response=new PostIdentificationResponse();
        try {
            JSONObject obj=paramFromReader(req.getReader());
            String baseImg=obj.getString("identificationCardImg");
            if (StringUtils.isEmpty(baseImg)) {
                return response.error();
            }
            BodyIDOCR idocr=businessService.postIDCard(auth.getUserId(),baseImg);
            response.setRealName(idocr.getName());
            response.setIdentificationCard(idocr.getNumber());
        } catch(Exception e) {
            return response.error();
        }

        return response.success();
    }

    /**
     * 从流里面取参数信息
     * @param reader
     * @return
     * @throws IOException
     */
    private JSONObject paramFromReader(BufferedReader reader) throws IOException {
        StringBuilder sb = new StringBuilder();
        char[] buff = new char[1024];
        int len = -1;
        while((len = reader.read(buff)) != -1) {
            sb.append(buff, 0, len);
        }
        reader.close();
        return JSONObject.parseObject(sb.toString());
    }

    /**
     * 获取银行列表信息
     * @return
     */
    @RequestMapping("getBankData")
    @ResponseBody
    public BankDataResponse getBankData(BankDataRequest bo){
        BankDataResponse response=new BankDataResponse();
        response.setBankList(businessService.selBankList(bo.getType(),bo.getBankName()));
        return response.success();
    }

    /**
     * 查询省份数据
     * @return
     */
    @RequestMapping("getProvData")
    @ResponseBody
    public ProvDataResponse getProvData(HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        ProvDataResponse response=new ProvDataResponse();
        response.setCommonlyList(businessService.selCommonlyProv(auth.getUserId()));
        response.setProvList(businessService.selProvs());
        return response.success();
    }

    /**
     * 按省ID查城市
     * @param bo
     * @return
     */
    @RequestMapping("getCityByProvId")
    @ResponseBody
    public CityDataResponse getCityByProvId(@Valid CityDataRequest bo,BindingResult result,HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        CityDataResponse response=new CityDataResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        response.setCityList(businessService.selCityByProvId(auth.getUserId(),bo.getProvId()));
        businessProcess.useProvRecord(auth.getUserId(),bo.getProvId());
        return response.success();
    }

    /**
     * 查区
     * @param bo
     * @param result
     * @return
     */
    @RequestMapping("getAreaByCityId")
    @ResponseBody
    public AreaDataResponse getAreaByCityId(@Valid AreaDataRequest bo,BindingResult result){
        AreaDataResponse response=new AreaDataResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        response.setAreaList(businessService.selAreaByCityId(bo.getCityId()));
        return response.success();
    }

    /**
     * 提交实名认证
     * @param bo
     * @param result
     * @param session
     * @return
     * @throws YeepayException
     */
    @RequestMapping("upCashCardInfo")
    @ResponseBody
    public UpCashCardInfoResponse upCashCardInfo(@Valid UpCashCardInfoRequest bo,BindingResult result,HttpSession session) throws PassagewayException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        UpCashCardInfoResponse response=new UpCashCardInfoResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }

        int checkResult=businessProcess.realCheck(auth.getUserId(),bo.getIdentificationCard(),bo.getUserRealName(),bo.getCashCard(),
                bo.getCardBank(),bo.getCardProv(),bo.getAreaId(),bo.getBankTelephone());
        if (checkResult==1) {
            businessService.businessAddShowAgent(auth.getUserId());
        }
        return response.success();
    }

    /**
     * 提交实名认证
     * @param bo
     * @param result
     * @param session
     * @return
     * @throws YeepayException
     */
    @RequestMapping("modifyCashCardInfo")
    @ResponseBody
    public UpCashCardInfoResponse modifyCashCardInfo(@Valid UpCashCardInfoRequest bo,BindingResult result,HttpSession session) throws PassagewayException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        UpCashCardInfoResponse response=new UpCashCardInfoResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        businessService.writeLinkNo(bo.getCardBank(),bo.getCashCard(),bo.getCardProv());
        businessProcess.modifyRealCheck(auth.getUserId(),bo.getIdentificationCard(),bo.getUserRealName(),bo.getCashCard(),
                bo.getCardBank(),bo.getCardProv(),bo.getAreaId(),bo.getBankTelephone());
        return response.success();
    }

    /**
     * 提交信用卡，OCR
     * @return
     */
    @RequestMapping("postCreditImg")
    @ResponseBody
    public PostCreditImgResponse postCreditImg(HttpServletRequest req,HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        PostCreditImgResponse response=new PostCreditImgResponse();
        try {
            JSONObject obj=paramFromReader(req.getReader());
            String baseImg=obj.getString("creditCardImg");
            if (StringUtils.isEmpty(baseImg)) {
                return response.error();
            }
            response.setCreditCard(businessService.postCashImg(auth.getUserId(),baseImg));
        } catch(Exception e) {
            return response.error();
        }
        return response.success();
    }

    /**
     * 保存信用卡
     * @return
     */
    @RequestMapping("upCreditCard")
    @ResponseBody
    public UpCreditCardResponse upCreditCard(@Valid UpCreditCardRequest bo,BindingResult result,HttpSession session) throws MoException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        UpCreditCardResponse response=new UpCreditCardResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        businessService.addCreditCard(auth.getUserId(),bo.getCreditCard(),bo.getBankName());
        return response.success();
    }

    /**
     * 信用卡列表
     * @param session
     * @return
     */
    @RequestMapping("getCreditCardsData")
    @ResponseBody
    public CreditDataResponse getCreditCardsData(HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        CreditDataResponse response=new CreditDataResponse();
        response.setCreditCardList(businessService.myCreditCards(auth.getUserId()));
        return response.success();
    }

    /**
     * 删除信用卡
     * @return
     */
    @RequestMapping("deleCreditCards")
    @ResponseBody
    public DeleCreditResponse deleCreditCards(@Valid DeleCreditRequest bo,BindingResult result,HttpSession session){
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        DeleCreditResponse response=new DeleCreditResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        businessService.deleteCreditCards(auth.getUserId(),bo.getDeleIds());
        return response.success();
    }

    /**
     * 刷卡
     * @param bo
     * @param result
     * @return
     */
    @RequestMapping("submitWithdrawalMoney")
    @ResponseBody
    public ReceiveResponse submitWithdrawalMoney(@Valid ReceiveRequest bo,BindingResult result,HttpSession session) throws PassagewayException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        ReceiveResponse response=new ReceiveResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        response.setUrl(businessService.receive(auth.getUserId(),bo.getCreditCardId(), Double.valueOf(bo.getWithdrawalMoney()),bo.getPassageId()));
        return response.success();
    }

    /**
     * 修改密码
     * @param bo
     * @param result
     * @return
     */
    @RequestMapping("submitNewPswToServer")
    @ResponseBody
    public SubmitNewPswResponse submitNewPswToServer(@Valid SubmitNewPswRequest bo,BindingResult result,HttpSession session) throws MoException {
        SubmitNewPswResponse response=new SubmitNewPswResponse();
        if (result.hasErrors()) {
            return response.error(result.getFieldError().getDefaultMessage());
        }
        Long userId= (Long) session.getAttribute(SessionEnum.TEMP_LOGUSER.toString());
        if (userId == null) {
            throw new MoException("系统错误");
        }
        businessService.changePwd(userId,bo.getNewPsw());
        return response.success();
    }

    /**
     * 获取用户交易数据
     * @return
     */
    @RequestMapping("getTradeData")
    @ResponseBody
    public TradeDataResponse getTradeData(HttpSession session){
        TradeDataResponse response=new TradeDataResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        TradeCountVO countVO=businessService.countMyTrade(auth.getUserId());
        response.setMonthTradeMoney(countVO.getMonthTradeMoney());
        response.setTodayTradeMoney(countVO.getTodayTradeMoney());
        response.setTradeList(businessService.selTradeDatas(auth.getUserId()));
        return response.success();
    }

    /**
     * 获取验证码图片
     * @return
     */
    @RequestMapping("getQrCodeImg")
    @ResponseBody
    public QrCodeResponse getQrCodeImg(HttpSession session){
        QrCodeResponse response=new QrCodeResponse();
//        response.setUrl(host+"wappage/buspage/regedit/from"+auth.getUserId());
        response.setUrl(host+"wap/qrimg.htm");
        return response.success();
    }

    /**
     * 设置常用信用卡
     * @return
     */
    @RequestMapping("selectCreditCard")
    @ResponseBody
    public MoResponse selectCreditCard(Long cardId,HttpSession session) throws MoException {
        if (cardId == null) {
            throw new MoException("请选择信用卡");
        }
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        businessService.setUsedCard(auth.getUserId(),cardId);
        return new MoResponse().success();
    }


    /**
     * 支付成功回调
     * @param bo
     * @param response
     * @throws IOException
     */
    @RequestMapping("payedCallBack")
    public void payedCallBack(PayedCallbackBO bo, HttpServletResponse response) throws IOException {
        try {
            businessService.paySucceed(bo);
        } catch (PassagewayException e) {
            logger.error("结算失败"+e.getMessage());
        }
        responseSuccess(response,"SUCCESS");
    }

    /**
     * 发送短信回调
     * @param bo
     * @param response
     * @throws IOException
     */
    @RequestMapping("msgedCallback")
    public void msgedCallback(MsgedCallbackBO bo, HttpServletResponse response) throws IOException {
        responseSuccess(response,"SUCCESS");
    }

    /**
     * 结算成功回调
     * @param bo
     * @param response
     * @throws IOException
     */
    @RequestMapping("settlementCallback")
    public void settlementCallback(SettlementCallbackBO bo,HttpServletResponse response) throws IOException {
        try {
            businessService.settlementSucceed(bo);
        } catch (YeepayException e) {
            logger.error("结算失败"+e.getMessage());
        }
        responseSuccess(response,"SUCCESS");
    }

    private void responseSuccess(HttpServletResponse response,String value) throws IOException {
        PrintWriter w=response.getWriter();
        w.print(value);
        w.flush();
        w.close();
    }

    @RequestMapping("banklimit")
    @ResponseBody
    public BankLimitResponse banklimit(Long pid){
        BankLimitResponse response=new BankLimitResponse();
        response.setSuccess(true);
        response.setList(businessService.selBankLimits(pid));
        return response;
    }

    /**
     * 通道选择
     * @return
     */
    @RequestMapping("passageWays")
    @ResponseBody
    public PassageWaysResponse passageWays(PassageWaysRequest bo,HttpSession session){
        PassageWaysResponse response=new PassageWaysResponse();
        response.setSuccess(true);
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        response.setPassageWays(businessService.selPassageWaysByUserId(auth.getUserId(),bo.getCreditCardId()));
        return response;
    }

    /**
     * 激活通道
     * @param bo
     * @return
     */
    @RequestMapping("activePassway")
    @ResponseBody
    public ActivePasswayResponse activePassway(ActivePasswayRequest bo,HttpSession session) throws PassagewayException {
        ActivePasswayResponse response=new ActivePasswayResponse();
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        response.setSuccess(true);
        businessService.activePassway(auth.getUserId(),bo.getPid());
        return response;
    }

    @RequestMapping("unpay")
    public String unpay(Long id,HttpSession session,Model model) throws UnpayException {
        AuthorityUser auth= (AuthorityUser) session.getAttribute(SessionEnum.LOGIN_USER.toString());
        model.addAttribute("payUrl",UNPAY_FRONTURL);
        model.addAttribute("data",businessService.unpayData(auth.getUserId(),id));
        return "unionpay";
    }

    /**
     *
     * 同步回调
     * {"merId":"847001257320035","msg":"交易已受理","orderId":"20180
     119112206001095","queryId":"471801191122068744228","reqReserved":"","signature":"58a48226bc89538bb41f72d52dca1c120bbeeecf04525e9772
     32843e6d1f785f","status":0,"success":true,"txnAmt":"10000","txnTime":"20180119112206","txnType":"01"}
     * @param bo
     * @return
     */
    @RequestMapping("unpayCallback")
    public String unpayCallback(ConsumptionResponse bo){
        try {
            businessService.unPayCallback(bo);
        } catch (PassagewayException e) {
            logger.error(e.getCode(),e);
        }
        return "redirect:/wappage/buspage/index";
    }

    /**
     * 异步回调
     * @param bo
     * @return
     */
    @RequestMapping("unpayAsyncCallback")
    @ResponseBody
    public String unpayAsyncCallback(@RequestBody ConsumptionResponse bo){
        try {
            businessService.unPayCallback(bo);
        } catch (PassagewayException e) {
            logger.error(e.getCode(),e);
        }
        return "ok";
    }

    @RequestMapping("tuiwxTest")
    @ResponseBody
    public String tuiwxTest(){
        businessService.tuiwx();
        return "test ok!!";
    }
}
